package com.haotunet.app.goldtreasure.activity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.UserInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Config;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.Timer;
import java.util.TimerTask;

import cn.tongdun.android.shell.FMAgent;

public class RegisterActivity extends BaseActivity implements OnClickListener {
    private TitleView mTitleView;
    private Button btnNext;
    private TextView mFetchBtn;
    private TextView mProcotolBtn;
    private ImageView mPwdStatus;
    private ImageView ivDeletePhone;
    private EditText mPhoneTxt, mPasswordTxt, mVeriCodeTxt, mRecommendNum;
    private CheckBox mProtocal;
    private ActionUtil actionUtil;
    private boolean pwdStatus = false;
    private int curTime;
    private Timer timer;
    private Handler doActionHandler = new Handler() {
        @SuppressWarnings("deprecation")
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (curTime == 0) {
                        timer.cancel();
                        mFetchBtn.setText("重新获取");
                        mFetchBtn.setTextColor(RegisterActivity.this.getResources().getColor(R.color.title_bg));
                        mFetchBtn.setEnabled(true);
                    } else {
                        mFetchBtn.setText(curTime + "s" + getString(R.string.repeat_after_sixty_seconds));
                        mFetchBtn.setTextColor(RegisterActivity.this.getResources().getColor(R.color.title_bg));
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private ShareStore mStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mStore = new ShareStore(this);
        initView();
    }

    private void initView() {
        actionUtil = new ActionUtil(RegisterActivity.this);
        mTitleView = (TitleView) findViewById(R.id.title_view);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText(getString(R.string.register));
        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnNext = (Button) findViewById(R.id.btn_next);
        mPhoneTxt = (EditText) findViewById(R.id.et_phoneNum);
        ivDeletePhone = (ImageView) findViewById(R.id.iv_delete_phone);
        mPasswordTxt = (EditText) findViewById(R.id.et_register_pwd);
        mVeriCodeTxt = (EditText) findViewById(R.id.et_vericode);
        mRecommendNum = (EditText) findViewById(R.id.et_invite_code);
        mFetchBtn = (TextView) findViewById(R.id.btn_get_register_vericode);
        mPwdStatus = (ImageView) findViewById(R.id.iv_pwd_status);
        mProcotolBtn = (TextView) findViewById(R.id.txt_protocol);
        mProtocal = (CheckBox) findViewById(R.id.cb_protocal);
        mProtocal.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mProtocal.setChecked(true);
                } else {
                    mProtocal.setChecked(false);
                }
            }
        });
        initEditext();
        mProcotolBtn.setOnClickListener(this);
        btnNext.setOnClickListener(this);
        mFetchBtn.setOnClickListener(this);
        ivDeletePhone.setOnClickListener(this);
        mPwdStatus.setOnClickListener(this);
    }

    private void initEditext() {
        mPhoneTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ivDeletePhone.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePhone.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_delete_phone:
                mPhoneTxt.setText("");
                break;
            case R.id.btn_get_register_vericode:
                String phone = mPhoneTxt.getText().toString().trim();

                if (TextUtils.isEmpty(phone)) {
                    UIHelper.showToast(RegisterActivity.this, getString(R.string.please_enter_phone_number));
                    return;
                }
                if (!Utils.isCellularPhoneNumber(phone)) {
                    UIHelper.showToast(RegisterActivity.this, getString(R.string.wrong_phone_number));
                } else {
                    getSmsVF(phone);
                }

                break;
            case R.id.btn_next:
                commit();
                break;
            case R.id.iv_pwd_status:
                if (pwdStatus) {
                    pwdStatus = false;
                    mPasswordTxt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mPwdStatus.setSelected(false);
                } else {
                    pwdStatus = true;
                    mPasswordTxt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mPwdStatus.setSelected(true);
                }
                break;
            case R.id.txt_protocol:
                ActivityUtils.gotoDynamicDetail(RegisterActivity.this, UrlUtil.SERVICE_PROTOCOL, 3);
                break;
            default:
                break;
        }
    }

    private void commit() {
        String phone = mPhoneTxt.getText().toString().trim();
        String vericode = mVeriCodeTxt.getText().toString().trim();
        String recommendNum = mRecommendNum.getText().toString().trim();
        String password = mPasswordTxt.getText().toString().trim();
        if (!mProtocal.isChecked()) {
            UIHelper.showToast(RegisterActivity.this, getString(R.string.agree_xieyi_can_register));
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            UIHelper.showToast(RegisterActivity.this, getString(R.string.please_enter_phone_number));
            return;
        }
        if (TextUtils.isEmpty(vericode)) {
            UIHelper.showToast(RegisterActivity.this, getString(R.string.please_enter_vericode));
            return;
        }
        if (TextUtils.isEmpty(password)) {
            UIHelper.showToast(RegisterActivity.this, getString(R.string.please_enter_pwd));
            return;
        }

        int length = password.length();
        if (length < Strs.MINLENGTH || length > Strs.MAXLENGTH || !Utils.isPassword(password)) {
            UIHelper.showToast(RegisterActivity.this,
                    getString(R.string.password_format_promat));
            return;
        }
        regist(phone, vericode, password, recommendNum);
    }

    private void regist(final String phone, String vericode, final String password, String recommendNum) {
        String imei = Config.getImei(RegisterActivity.this);
        String device_token = Config.getUmengToken(RegisterActivity.this);
        //获取渠道名
        String umeng_channel = Config.getStringMetaData(RegisterActivity.this, "UMENG_CHANNEL");
        String blackBox = FMAgent.onEvent(this);
        actionUtil.AddRegisterInfo(umeng_channel, blackBox, phone, vericode, password, recommendNum, imei, device_token);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                UserInfo info = (UserInfo) model;
                if (info == null) {
                    UIHelper.showToast(RegisterActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    UIHelper.showToast(RegisterActivity.this, model.getErrorMsg());
                } else {
                    UIHelper.showToast(RegisterActivity.this, getString(R.string.register_success));
                    storeUserInfo(info);
                    ActivityUtils.skipToMain(RegisterActivity.this, "register");
                }
            }
        });
    }

    private void storeUserInfo(UserInfo info) {
        mStore.putBoolean(Strs.IS_LOGIN, true);
        mStore.commit();
        DBOpenHelper helper = new DBOpenHelper(RegisterActivity.this);
        SQLiteDatabase db = helper.getReadableDatabase();
        String mobile = info.getUserName();
        String sql = "select * from HJB_USER where mobile = " + "'" + mobile + "'";
        Cursor rawQuery = db.rawQuery(sql, null);
        if (rawQuery.getCount() != 0) {
            helper.updateUser(mobile, "0", info);
        } else {
            helper.insertUser("0", info);
        }
    }

    private void getSmsVF(String phone) {
        String blackBox = FMAgent.onEvent(RegisterActivity.this);
        String imei = Config.getImei(RegisterActivity.this);
        actionUtil.getRegisterCode(phone, blackBox, imei);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(RegisterActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    UIHelper.showToast(RegisterActivity.this, model.getErrorMsg());
                } else {
                    UIHelper.showToast(RegisterActivity.this, getString(R.string.vericode_send_success));
                    setTimerTask();
                    mFetchBtn.setEnabled(false);
                }
            }
        });
    }

    private void setTimerTask() {
        curTime = 60;
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                Message msg = new Message();
                msg.what = 1;
                doActionHandler.sendMessage(msg);
                curTime--;
            }
        }, 0, 1000);
    }
}
